(function () {
  let lastTriggerTs = 0;
  let modifierKey = "Alt";
  let triggerKey = "LeftClick";

  // 从存储中加载快捷键配置
  chrome.storage.sync.get({modifierKey: "Alt", triggerKey: "LeftClick"}, (cfg) => {
    modifierKey = cfg.modifierKey;
    triggerKey = cfg.triggerKey;
  });

  // 监听配置变化
  chrome.storage.onChanged.addListener((changes) => {
    if (changes.modifierKey) modifierKey = changes.modifierKey.newValue;
    if (changes.triggerKey) triggerKey = changes.triggerKey.newValue;
  });

  // 判断是否按下了正确的修饰键
  function isModifierKeyPressed(e) {
    switch(modifierKey) {
      case "Alt": return e.altKey;
      case "Ctrl": return e.ctrlKey;
      case "Shift": return e.shiftKey;
      case "Meta": return e.metaKey;
      default: return e.altKey;
    }
  }

  // 判断是否按下了正确的触发键
  function isTriggerKeyPressed(e) {
    // 0: 左键, 2: 右键
    return triggerKey === "LeftClick" ? e.button === 0 : e.button === 2;
  }

  function getSelectedText() {
    const sel = window.getSelection();
    if (!sel) return "";
    return (sel.toString() || "").trim();
  }

  function handleMouseDown(e) {
    if (!isModifierKeyPressed(e) || !isTriggerKeyPressed(e)) return;

    const now = Date.now();
    if (now - lastTriggerTs < 300) return;
    lastTriggerTs = now;

    const target = e.target;
    const linkEl = target && target.closest("a[href]");

    if (linkEl) {
      const link = linkEl.href;
      const screenX = window.screenX + e.clientX;
      const screenY = window.screenY + e.clientY;

      chrome.runtime.sendMessage({
        type: "OPEN_LINK_IN_POPUP",
        url: link,
        screenX,
        screenY
      });

      e.preventDefault();
      e.stopImmediatePropagation();
    } else {
      const text = getSelectedText();
      if (text && text.length >= 1) {
        const screenX = window.screenX + e.clientX;
        const screenY = window.screenY + e.clientY;
        chrome.runtime.sendMessage({
          type: "OPEN_SEARCH_WINDOW",
          text,
          screenX,
          screenY
        });
      }
    }
  }

  function handleClick(e) {
    if (!isModifierKeyPressed(e) || !isTriggerKeyPressed(e)) return;

    const target = e.target;
    const linkEl = target && target.closest("a[href]");
    if (linkEl) {
      e.preventDefault();
      e.stopImmediatePropagation();
    }
  }
  // 如果支持右键触发，需要阻止默认右键菜单
  window.addEventListener("contextmenu", (e) => {
    if (isModifierKeyPressed(e) && triggerKey === "RightClick") {
      e.preventDefault();
      e.stopImmediatePropagation();
    }
  }, true);

  window.addEventListener("mousedown", handleMouseDown, true);
  window.addEventListener("click", handleClick, true);

  // -------- 只在扩展 popup 小窗中拦截点击 --------
  if (new URLSearchParams(location.search).get("popup") === "1") {
    document.addEventListener(
        "click",
        (e) => {
          const link = e.target.closest("a[href]");
          if (link && link.href) {
            e.preventDefault();
            location.href = link.href;
          }
        },
        true
    );
  }
})();
